package com.pacific.sign.biz.wrapper.aop;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Aspect
@Component
/**
 * AOP日志打印
 */
public class HcAop {
	
	private final Logger log = LogManager.getLogger();


	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Around(value = "com.pacific.sign.biz.wrapper.aop.HcPointCut.logAnnotation()&&@annotation(logAnnotation)",
			argNames = "logAnnotation")
	public Object doAround(ProceedingJoinPoint pjp,LogAnnotation logAnno) throws Throwable {
		return doSomeThing(pjp,logAnno.value(),ThreadLocalUtils.getLogPrefix());
	}
	
	public Object doSomeThing(ProceedingJoinPoint pjp,String logvalue,String uuid) throws Throwable{
		// 调用方法的参数
		Object[] args = pjp.getArgs();
		String req = HcAopUtil.getStringFromRequest(args);
		pjp.getSignature().getName();
		// 获取目标对象的类名(形如：com.action.admin.LoginAction)
		String targetName = pjp.getTarget().getClass().getName()+"."+pjp.getSignature().getName();
		// 执行完方法的返回值：调用proceed()方法，就会触发切入点方法执行
		// result的值就是被拦截方法的返回值
		Object result = null;
		long start = System.currentTimeMillis();
		try{
			result = pjp.proceed();
		}catch(Exception e){
			log.error(req,e);
			throw e;
		}
		long end = System.currentTimeMillis();
		Object show = HcAopUtil.getStringFromResponse(result);
		
		String msg = "\nlog - {0}  " +
				"/******************************************************************************" +
				"[**UUID**]={1} request [*****] {2}response [*****] {3}consume [*****] {4}ms\n" +
				"******************************************************************************/\n";
		log.info(MessageFormat.format(msg, new Object[] { targetName+"=["+logvalue+"]",uuid,
				req, show.toString(),(end-start) }));
		return result;
	}
	
}